package main

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
)

// 不安全，明文
// 增加带宽消耗
// 可以被禁用
// cookie有上限

func main() {
	r := gin.Default()

	r.GET("/login", func(c *gin.Context) {
		cookie, err := c.Cookie("key_cookie")
		if err != nil {
			// cookie = time.Now().Local().String()
			cookie = "lxd-cookie-set"
			// 给客户端设置cookie
			// maxAge: 声明周期, 单位 => s
			// path: cookie所在目录
			// domain: 域名
			// secure: 是否只能通过https访问
			// httpOnly: 是否允许别人通过js获取自己的cookie，false:可以在console中通过document.cookie获取，true:不行
			c.SetCookie("key_cookie", cookie, 60, "/", "localhost", false, false)
		}

		c.String(http.StatusOK, "Login success!!")
		fmt.Printf("cookie is:%s\n", cookie)
	})

	r.GET("/home", AuthMiddleWare, func(c *gin.Context) {
		c.String(http.StatusOK, "Welcome to xiao's website ^.^")
	})

	r.Run(":80")
}

func AuthMiddleWare(c *gin.Context) {
	var s_err string
	cookie, err := c.Cookie("key_cookie")
	if err == nil {
		if cookie == "lxd-cookie-set" {
			c.Next()
			return
		} else {
			s_err = "cookie error"
		}
	} else {
		s_err = "cookie not found"
	}
	c.String(http.StatusUnauthorized, s_err)
	c.Abort()
}
